package com.cx.common.utils;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * @Author:cxy
 * @Date:2019/10/24 15:11
 * 
 */
public class ByteUtils {

	/**
	 * This method will convert a big decimal value to bytes
	 *
	 * @param num
	 * @return
	 */
	public static byte[] bigDecimalToByte(BigDecimal num) {
		BigInteger sig = new BigInteger(num.unscaledValue().toString());
		int scale = num.scale();
		byte[] bscale = { (byte) (scale) };
		byte[] buff = sig.toByteArray();
		byte[] completeArr = new byte[buff.length + bscale.length];
		System.arraycopy(bscale, 0, completeArr, 0, bscale.length);
		System.arraycopy(buff, 0, completeArr, bscale.length, buff.length);
		return completeArr;
	}

	/**
	 * This method will convert a byte value back to big decimal value
	 *
	 * @param raw
	 * @return
	 */
	public static BigDecimal byteToBigDecimal(byte[] raw) {
		int scale = (raw[0] & 0xFF);
		byte[] unscale = new byte[raw.length - 1];
		System.arraycopy(raw, 1, unscale, 0, unscale.length);
		BigInteger sig = new BigInteger(unscale);
		return new BigDecimal(sig, scale);
	}

	/**
	 * This method will convert a byte value back to big decimal value
	 *
	 * @param raw
	 * @return
	 */
	public static BigDecimal byteToBigDecimal(byte[] raw, int offset, int length) {
		int scale = (raw[offset] & 0xFF);
		byte[] unscale = new byte[length - 1];
		System.arraycopy(raw, offset + 1, unscale, 0, unscale.length);
		BigInteger sig = new BigInteger(unscale);
		return new BigDecimal(sig, scale);
	}
}
